import React from 'react';
import { inject, observer } from 'mobx-react';
import {Button,Spin,Modal,Icon} from 'antd';
import { WeaDialog,WeaNewScroll,WeaLocaleProvider,WeaFormItem,WeaSearchGroup,WeaInput,WeaBrowser,WeaDatePicker,WeaTools,WeaUpload,WeaRichText,WeaTextarea,WeaInputNumber,WeaPopoverHrm} from 'ecCom';
import NewLinkeb from '../../public/newlinked/NewLinkeb';
import * as Util from '../../util/Util.js';
import TaskDetailDialog from './../task/TaskDetailDialog';
const getLabel = WeaLocaleProvider.getLabel;
@inject('planDetailViewStore')
@observer
export default class PlanDetailView extends React.Component {
    constructor(props) {
        super(props);
        this.state ={
            key:this.props.detailid,
            showvisible:false,
            showKey:'',
            locationkey:new Date().getTime()
        }
        this.mirror = {
            37: "/spa/document/index.jsp?id=",
            7: "/spa/crm/mobx/index.html#/main/crm/customerView?customerId=",
            152: "/workflow/request/ViewRequestForwardSPA.jsp?requestid=",
            8: "/spa/prj/index.html#/main/prj/projectCard?prjid=",
            1:'/spa/hrm/index_mobx.html#/main/hrm/card/cardInfo/',
        }
    }
    componentWillMount() {//一些初始化请求
        const{planDetailViewStore,canedit,datatype,detailid} = this.props;
        planDetailViewStore.getDetailView({plandetailid:detailid,datatype:datatype,canedit:canedit});
    }
    getButton = ()=>{
        let buttonsCreate = [
            (<Button type="primary" onClick={this.onClose.bind(this)}>保存</Button>),
            (<Button type="ghost" onClick={this.onClose.bind(this)}>关闭</Button>)
        ];
        return buttonsCreate;
    }
    onClose(){
        if(typeof this.props.onClose === "function"){
            this.props.onClose()
        }
    }
    onInputChange(val,type){
        let{planDetailViewStore,resourceid} = this.props;
        planDetailViewStore.editParams[type] = val;
        planDetailViewStore.saveDetailView({fieldname:type,fieldvalue:val,plandetailid:this.state.key,resourceid:resourceid,fieldtype:'str'});
    }
    onDateChange(val,type){
        let{planDetailViewStore,resourceid} = this.props;
        let flag = true;
        let days = 0;
        let tip = "";
        let col = "";
        if(val!=""){
            if(type=="begindate2" && planDetailViewStore.editParams["enddate2"]!=""){
                days = Util.DateDiffDays(val,planDetailViewStore.editParams["enddate2"]);
                if(days<0){
                    flag = false;
                    tip = "实际开始日期不能大于实际结束日期!";
                }else{
                    col = "days2";
                }
            }else if(type=="enddate2" && planDetailViewStore.editParams["begindate2"]!=""){
                days = Util.DateDiffDays(planDetailViewStore.editParams["begindate2"],val);
                if(days<0){
                    flag = false;
                    tip = "实际结束日期不能小于实际开始日期!";
                }else{
                    col = "days2";
                }
            }else if(type=="begindate1" && planDetailViewStore.editParams["enddate1"]!=""){
                days = Util.DateDiffDays(val,planDetailViewStore.editParams["enddate1"]);
                if(days<0){
                    flag = false;
                    tip = "计划开始日期不能大于计划结束日期!";
                }else{
                    col = "days1";
                }
            }else if(type=="enddate1" && planDetailViewStore.editParams["begindate1"]!=""){
                days = Util.DateDiffDays(planDetailViewStore.editParams["begindate1"],val);
                if(days<0){
                    flag = false;
                    tip = "计划结束日期不能小于计划开始日期!";
                }else{
                    col = "days1";
                }
            }
        }
        if(flag){
            planDetailViewStore.canView = false;
            planDetailViewStore.editParams[type] = val;
            if(col!=""){
                planDetailViewStore.editParams[col] = days;
            }
            planDetailViewStore.saveDetailView({fieldname:type,fieldvalue:val,plandetailid:this.state.key,resourceid:resourceid,fieldtype:'str',
                                                otherfield:col,othervalue:days});
            planDetailViewStore.canView = true;
        }else{
            planDetailViewStore.canView = false;
            Modal.warning({
                title: "提示",
                content: tip,
            });
            planDetailViewStore.canView = true;
        }
    }
    onChangeBrowser(ids, names, datas, typeIds, typeArray){
        let{planDetailViewStore,resourceid} = this.props;
        if (ids.length > 0) {
            let idsArray = ids.split(',');
            let namesArray = names.split(',');
            if(planDetailViewStore.editParams[typeIds]==undefined){
                planDetailViewStore.editParams[typeIds] = '';
                planDetailViewStore.editParams[typeArray] = [];
            }
            for (let i = 0; i < idsArray.length; i++) {
                if (planDetailViewStore.editParams[typeIds].indexOf(',' + idsArray[i] + ',') == -1) {
                    planDetailViewStore.editParams[typeArray].push({ id: idsArray[i], name: namesArray[i] });
                    if (planDetailViewStore.editParams[typeIds] == '') {
                        planDetailViewStore.editParams[typeIds] = ',';
                    }
                    planDetailViewStore.editParams[typeIds] += idsArray[i] + ',';
                }
            }
            planDetailViewStore.canEdit = false;
            planDetailViewStore.saveDetailView({fieldname:typeIds,fieldvalue:planDetailViewStore.editParams[typeIds],plandetailid:this.state.key,resourceid:resourceid,fieldtype:'str'});
        }
    }
    /**上传附件 */
    uploadChange(ids, list) {
        let { planDetailViewStore,resourceid } = this.props;
        if (ids.length > 0) {
            let newAddFileids = '';
            if(planDetailViewStore.editParams['fileids']==undefined){
                planDetailViewStore.editParams['fileids'] = '';
                planDetailViewStore.editParams['filearray'] = [];
            }
            for (let i = 0; i < list.length; i++) {
                let fileA = {};
                if (planDetailViewStore.editParams.fileids.indexOf(',' + ids[i] + ',') == -1) {
                    planDetailViewStore.editParams.fileids += ids[i] + ',';
                    fileA.id = ids[i];
                    fileA.name = list[i].filename;
                    planDetailViewStore.editParams.filearray.push(fileA);
                }
            }
            planDetailViewStore.canEdit = false;
            planDetailViewStore.saveDetailView({fieldname:"fileids",fieldvalue:planDetailViewStore.editParams['fileids'],plandetailid:this.state.key,resourceid:resourceid});
        }
    }
    onLinkClick(id, name, type, typeIds, typeArray){
        let { planDetailViewStore,resourceid } = this.props;
        if (type == 2) {//删除
            let sendValue ='';
            let fieldtype = 'str';
            let vals = planDetailViewStore.editParams[typeIds];
            if (vals.length > 0 && !Util.startWith(vals, ',')) {
                vals = ',' + vals;
            }
            if (vals.length > 0 && !Util.endWith(vals, ',')) {
                vals = vals + ',';
            }
            let _index = vals.indexOf("," + id + ",")
            if (_index > -1 && id != "") {
                vals = vals.substring(0, _index + 1) + vals.substring(_index + (id + "").length + 2);
                if (vals == ',') {
                    vals = '';
                }
                planDetailViewStore.editParams[typeIds] = vals;
                if (typeIds == 'fileids') {//附件
                    sendValue = id;
                    fieldtype = 'del';
                }else { //其他
                    sendValue = vals;
                }
            }
            //对array进行处理
            let array = planDetailViewStore.editParams[typeArray];
            array.map((elemnet, index) => {
                if (elemnet.id == id) {
                    planDetailViewStore.editParams[typeArray].remove(elemnet);
                }
            });
            planDetailViewStore.canEdit = false;
            planDetailViewStore.saveDetailView({fieldname:typeIds,fieldvalue:sendValue,plandetailid:this.state.key,resourceid:resourceid,fieldtype:fieldtype});
        }else if(type==1 && typeIds == "taskids"){
            this.setState({showvisible:true,locationkey:new Date().getTime(),showKey:id});
        }
    }
     //反馈 发布
    planRelease(){
        const { planDetailViewStore} = this.props;
        if (planDetailViewStore.feedbackContent != '') {
            planDetailViewStore.saveDetailView({plandetailid:this.state.key,content: planDetailViewStore.feedbackContent,operation:'add_feedback'});
        } else {
            Modal.warning({
                title: "提示",
                content: '反馈信息不能为空!',
            });
        }
    }
    setfeedbackContent(v){
        const { planDetailViewStore } = this.props;
        planDetailViewStore.feedbackContent = v;
    }
    onMoreFeedbackClick(){
        const { planDetailViewStore } = this.props;
        planDetailViewStore.getFbInfo({plandetailid:this.state.key});
    }
    //category-目录id  detailid-计划明细id style-dialog宽高等 resourceid-当前报告的所属人id visible-控制dialog显隐
    render() {
        const{planDetailViewStore,category,visible} = this.props;
        const{locationkey,showvisible,showKey} = this.state;
        let {spinning,editParams,emptyArray,showtask,canEdit,canView,feedbackContent,fblist,fblastcount,customList} = planDetailViewStore;
        return (
            <WeaDialog
				visible={visible}
				title={'计划详情'}
				icon="icon-coms-Journal"
				iconBgcolor="#7734FF"
				className="createWorkPlan"
				buttons={this.getButton()}
                style={this.props.style || {width:'900px',height:window.innerHeight - 140}}
                closable= {true}
				onCancel={this.onClose.bind(this)}
			>
			 <div className="workrelate-plan-detailview">
                <Spin spinning={spinning}>
                    <WeaNewScroll height={this.props.style?this.props.style.height:window.innerHeight - 190}>
                        <WeaPopoverHrm />
                        <WeaSearchGroup title="基本信息" needTigger={true} showGroup={true}>
                            {customList && customList.length>0 && customList.map((elemnet,idx)=>{
                                return <WeaFormItem label={elemnet.showname} labelCol={{span: 4}} wrapperCol={{span: 18}} className={elemnet.inputtype==3?"plan-item-"+elemnet.fieldname:""}>
                                          {elemnet.inputtype==1 && <WeaInput onBlur = {(value) =>  this.onInputChange(value,elemnet.fieldname)} value={editParams[elemnet.fieldname]}
                                                                    placeholder={"请输入"+elemnet.showval}   inputType={"multilang"} viewAttr={canView && elemnet.isEdit?2:1}/>}
                                          {elemnet.inputtype==2 && <WeaTextarea onBlur={value => this.onInputChange(value,elemnet.fieldname)}  inputType={"multilang"} value={editParams[elemnet.fieldname]} viewAttr={canView && elemnet.isEdit?2:1}/>}
                                          {elemnet.inputtype==3 && <WeaDatePicker onChange={value =>this.onDateChange(value,elemnet.fieldname)} value={editParams[elemnet.fieldname]} viewAttr={canView && elemnet.isEdit?2:1}/>}
                                          {elemnet.inputtype==4 && <WeaInputNumber value={editParams[elemnet.fieldname]} viewAttr={canView && elemnet.isEdit?2:1} onChange={value => this.onInputChange(value,elemnet.fieldname)}/>}
                                       </WeaFormItem>
                            })}
                        </WeaSearchGroup >
                        <WeaSearchGroup title="相关信息" needTigger={true} showGroup={true}>
                            {showtask && <WeaFormItem label="相关任务" labelCol={{ span: 4 }} wrapperCol={{ span: 18 }} className='plan-item-task'>
                                <div className="xgrw-div">
                                    <div className="linked-div"><NewLinkeb onLinkClick={(id, name, type) => this.onLinkClick(id, name, type, "taskids", 'taskarray')} linkdatas={editParams.taskarray} hasdel={canEdit} /></div>
                                    {canEdit && <div className="xgrw-edit"><WeaBrowser onChange={(ids, names, datas) => { this.onChangeBrowser(ids, names, datas, "taskids", 'taskarray') }}
                                        title="相关任务" type="wrltsk" viewAttr={2} isSingle={false} inputStyle={{ width: 100 }}/></div>}
                                </div>
                            </WeaFormItem>}
                            <WeaFormItem label="相关文档" labelCol={{ span: 4 }} wrapperCol={{ span: 18 }} className='plan-item-doc'>
                                <div className="xgwd-div">
                                  <div className="linked-div"><NewLinkeb linkurl={this.mirror[37]} onLinkClick={(id, name, type) => this.onLinkClick(id, name, type, "docids", 'docarray')} linkdatas={editParams.docarray} hasdel={canEdit} /></div>
                                  {canEdit && <div className="xgwd-edit"><WeaBrowser title="相关文档" type={9} inputStyle={{ width: 100 }}
                                        onChange={(ids, names, datas) => this.onChangeBrowser(ids, names, datas, "docids", 'docarray')} isSingle={false} /></div>}
                                </div>
                            </WeaFormItem>
                            <WeaFormItem label="相关流程" labelCol={{ span: 4 }} wrapperCol={{ span: 18 }} className='plan-item-wf'>
                                <div className="xglc-div">
                                   <div className="linked-div"><NewLinkeb onLinkClick={(id, name, type) => this.onLinkClick(id, name, type, "wfids", 'wfarray')} linkurl={this.mirror[152]} linkdatas={editParams.wfarray} hasdel={canEdit} /></div>
                                   {canEdit && <div className="xglc-edit"><WeaBrowser title="相关流程" type={16} inputStyle={{ width: 100 }} onChange={(ids, names, datas) => this.onChangeBrowser(ids, names, datas, "wfids", 'wfarray')}
                                        isSingle={false} /></div>}
                                </div>
                            </WeaFormItem>
                            <WeaFormItem label="相关客户" labelCol={{ span: 4 }} wrapperCol={{ span: 18 }} className='plan-item-crm'>
                                <div className="xgkh-div">
                                   <div className="linked-div"><NewLinkeb  linkurl={this.mirror[7]}  onLinkClick={(id, name, type) => this.onLinkClick(id, name, type, "crmids", 'crmarray')} linkdatas={editParams.crmarray} hasdel={canEdit} /></div>
                                   {canEdit &&<div className="xgkh-edit"><WeaBrowser title="相关客户" type={7} inputStyle={{ width: 100 }}
                                        onChange={(ids, names, datas) => this.onChangeBrowser(ids, names, datas, "crmids", 'crmarray')} isSingle={false} /></div>}
                                </div>
                            </WeaFormItem>
                            <WeaFormItem label="相关项目" labelCol={{ span: 4 }} wrapperCol={{ span: 18 }} className='plan-item-project'>
                                <div className="xgxm-div">
                                    <div className="linked-div"><NewLinkeb linkurl={this.mirror[8]} onLinkClick={(id, name, type) => this.onLinkClick(id, name, type, "projectids", 'projectarray')}  linkdatas={editParams.projectarray} hasdel={canEdit} /></div>
                                    {canEdit &&<div className="xgxm-edit"><WeaBrowser title="相关项目" type={8} inputStyle={{ width: 100 }}
                                            onChange={(ids, names, datas) => this.onChangeBrowser(ids, names, datas, "projectids", 'projectarray')} isSingle={false} /></div>}
                                </div>
                            </WeaFormItem>
                            <WeaFormItem label="相关附件" labelCol={{ span: 4 }} wrapperCol={{ span: 18 }} className='plan-item-file'>
                                <div className="xgfj-div">
                                   <div className="linked-div"><NewLinkeb onLinkClick={(id, name, type) => this.onLinkClick(id, name, type, "fileids", 'filearray')} linkurl='' linkdatas={editParams.filearray} hasdel={canEdit} /></div>
                                   {canEdit &&<div className="xgfj-edit"><WeaUpload uploadUrl={'/api/workrelate/common/uploadDoc?category='+category} category={category}
                                        viewAttr='1' showClearAll={false}  onChange={(ids, list) => this.uploadChange(ids, list)} /></div>}
                                </div>
                            </WeaFormItem>
                        </WeaSearchGroup>
                        <WeaSearchGroup title="反馈信息" needTigger={true} showGroup={true}>
                            <WeaRichText
                                onChange={v => this.setfeedbackContent(v)}
                                value={feedbackContent}
                                ckConfig={{
                                    toolbar: [
                                        { name: 'document', items: ['Source'] },
                                        { name: 'paragraph', items: ['JustifyLeft', 'JustifyCenter', 'JustifyRight', '-', 'NumberedList', 'BulletedList'] },
                                        { name: 'styles', items: ['Format', 'Font', 'FontSize'] },
                                        { name: 'colors', items: ['TextColor'] },
                                        { name: 'basicstyles', items: ['Bold', 'Italic', 'Underline', 'Strike',] },
                                        { name: 'insert', items: ['Table', 'Smiley'] }
                                    ],
                                    height: 80,
                                    startupFocus: false,
                                    autoGrow_minHeight: 80,
                                    autoGrow_maxHeight: 80,
                                }}
                                extentsConfig
                                bottomBarConfig={[
                                    {
                                        name: 'Upload', // 上传组件
                                        show: <span style={{ fontSize: 12 }}>
                                            <Icon type='paper-clip' title='上传附件' /> 附件</span>, // 使用 antd 图标
                                        uploadUrl: '/api/workrelate/common/uploadDoc?category='+category, // 上传地址
                                        category: category, // 文档目录
                                    },
                                    {
                                        name: 'Browser', // 浏览按钮组件
                                        show: <span style={{ fontSize: 12 }}>
                                            <i className='icon-coms-Journal' title='文档' /> 文档</span>, // 使用组件库图标
                                        type: '37', // 浏览按钮类型 文档
                                        title: '文档', // 浏览按钮标题
                                    },
                                    {
                                        name: 'Browser', // 浏览按钮组件
                                        show: <span style={{ fontSize: 12 }}>
                                            <i className='icon-coms-Workflow-o' title='流程' /> 流程</span>,
                                        type: '152', // 浏览按钮类型
                                        title: '流程', // 浏览按钮标题
                                    },
                                    {
                                        name: 'Browser',
                                        show: <span style={{ fontSize: 12 }}>
                                            <i className='icon-coms-meeting' title='客户' /> 客户</span>, // 使用组件库图标
                                        type: '7',
                                        title: '客户',
                                    },
                                    {
                                        name: 'Browser',
                                        show: <span style={{ fontSize: 12 }}>
                                            <i className='icon-coms-Top-floor' title='项目' /> 项目</span>,
                                        type: '8',
                                        title: '项目',
                                    }
                                ]}
                                bottomBarRight={{
                                    width: 100,
                                    Component: [
                                        <span className="wea-rich-text-toolbar-bottom-item" style={{ position: "relative" }}>
                                            <Button className="wea-button-release" onClick={() => this.planRelease()}>
                                                <span><span className="icon-coms-Release" /><span style={{ marginLeft: '2px' }}>提交</span></span>
                                            </Button>
                                        </span>
                                    ]
                                }}
                                onToolsChange={(name, ids, list, type) => Util.transfStr(name, ids, list, type,this.mirror)}
                            />
                            {
                                fblist && fblist.length > 0 && fblist.map((elemnet, index) => {
                                    return <div className="plan-detail-feedback">
                                            <div className="plan-detail-feedback-left"><a href='javaScript:void(0)' onClick={e => { openhrm(elemnet.hrmid); window.pointerXY(e) }} title={elemnet.hrmname} ><Icon type="user" /></a></div>
                                            <div className="plan-detail-feedback-right">
                                                <div className="plan-detail-feedback-right-name"><a href='javaScript:void(0)' onClick={e => { openhrm(elemnet.hrmid); window.pointerXY(e) }} title={elemnet.hrmname} >{elemnet.hrmname}</a></div>
                                                <div className="plan-detail-feedback-right-content" dangerouslySetInnerHTML={{ __html: elemnet.content }}></div>
                                                <div className="plan-detail-feedback-last-time">{elemnet.datetime}</div>
                                            </div>
                                        </div>
                                })
                            }
                            {fblastcount > 0 && <div className="tabs-Feedback-more" onClick={() => this.onMoreFeedbackClick()}>加载更多 <Icon type="down" /></div> }
                        </WeaSearchGroup>
                        <TaskDetailDialog detailKey={showKey} locationkey={locationkey} visable={showvisible}
                         onlyClose = {()=>this.setState({ showvisible: false })}  style={{width: 900, height: this.props.style?this.props.style.height:window.innerHeight - 140}} />
                    </WeaNewScroll>
			    </Spin>
                </div>
			</WeaDialog>
        )
    }
};